package com.woke.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatDialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.bean.AreaCode;
import com.bean.CountyAreaCode;
import com.http.HttpMethods;
import com.woke.adapter.AreaViewProvider;
import com.woke.adapter.CountyViewProvider;
import com.woke.adapter.OnItemClickListener;
import com.woke.method.NetworkUtils;
import com.zhongcai.online.R;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by Administrator on 2017/5/10 0010.
 * 浦发省市
 */

public class ProvincesAndCitiesDialogFragment extends AppCompatDialogFragment implements DialogInterface.OnKeyListener {

    private OnItemClickListener mItemClickListener;
    private MultiTypeAdapter mPMulitypeAdapter, mCityMulitypeAdapter, mCountyMulitypeAdapter;
    private Items mProvinceItems = new Items();
    private Items mCityItems = new Items();
    private Items mCountyItems = new Items();
    private RecyclerView mProvinceRecyclerView;
    private RecyclerView mCityRecyclerView;
    private RecyclerView mCountyRecyclerView;
    private ViewSwitcher mViewSwitcher, mSecondViewSwitcher;
    private int pageInde = 0;
    private AreaCode mProvinceAreaCode, mCityAreaCode;
    private CountyAreaCode mCountyAreaCode;
    private boolean isNeedCountyCode = true;  //是否需要 县级地区码

    public AreaCode getProvinceAreaCode() {
        return mProvinceAreaCode;
    }

    public AreaCode getCityAreaCode() {
        return mCityAreaCode;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mItemClickListener = listener;
    }

    public void needCountyCode(boolean isNeedCountyCode) {
        this.isNeedCountyCode = isNeedCountyCode;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme);
    }

//    @Nullable
//    @Override
//    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        View rootView = inflater.inflate(R.layout.fragment_dialog_provinces_and_cities, container, false);
//        mProvinceRecyclerView = (RecyclerView) rootView.findViewById(R.id.province_recyclerView);
//        mCityRecyclerView = (RecyclerView) rootView.findViewById(R.id.city_recyclerView);
//        mViewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher);
//        Toolbar mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
//        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (pageInde >= 1) {
//                    mViewSwitcher.showPrevious();
//                    pageInde--;
//                } else {
//                    dismiss();
//                }
//            }
//        });
//        initProvince();
//        initCity();
//        getProvincesData();
//        return rootView;
//    }

    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);

        Context context = dialog.getContext();
        View rootView = LayoutInflater.from(context).inflate(R.layout.fragment_dialog_provinces_and_cities, null);
        mProvinceRecyclerView = (RecyclerView) rootView.findViewById(R.id.province_recyclerView);
        mCityRecyclerView = (RecyclerView) rootView.findViewById(R.id.city_recyclerView);
        mCountyRecyclerView = (RecyclerView) rootView.findViewById(R.id.county_recyclerView);
        mViewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher);
        mSecondViewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.secondViewSwitcher);
        Toolbar mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pageInde > 1) {
                    mSecondViewSwitcher.showPrevious();
                    pageInde--;
                } else if (pageInde > 0) {
                    mViewSwitcher.showPrevious();
                    pageInde--;
                } else {
                    dismiss();
                }
            }
        });
        initProvince();
        initCity();
        initCounty();
        dialog.setContentView(rootView);
        getProvincesData();

        dialog.setOnKeyListener(this);
    }

    private void getProvincesData() {
        if (NetworkUtils.isConnected(getContext())) {
            HttpMethods.getInstance().getProvinceAreaCode(mAreaListObserver);
        } else {
            showToast(getResources().getString(R.string.hint_error_server));
            dismiss();
        }
    }

    private void getCitiesData(String areaCode) {
        if (NetworkUtils.isConnected(getContext())) {
            HttpMethods.getInstance().getCityAreaCode(mAreaListObserver, areaCode);
        } else {
            showToast(getResources().getString(R.string.hint_error_server));
        }
    }

    private void getCountysData(String city_no) {
        if (NetworkUtils.isConnected(getContext())) {
            HttpMethods.getInstance().getCountyCode(mCountyAreaCodeObserver, city_no);
        } else {
            showToast(getResources().getString(R.string.hint_error_server));
        }
    }

    private void initCounty() {
        mCountyRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mCountyMulitypeAdapter = new MultiTypeAdapter();
        mCountyMulitypeAdapter.register(CountyAreaCode.class, new CountyViewProvider(listener));
        mCountyRecyclerView.setAdapter(mCountyMulitypeAdapter);

        mCountyMulitypeAdapter.setItems(mCountyItems);
        mCountyMulitypeAdapter.notifyDataSetChanged();
    }


    private void initCity() {
        mCityRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mCityMulitypeAdapter = new MultiTypeAdapter();
        mCityMulitypeAdapter.register(AreaCode.class, new AreaViewProvider(listener));
        mCityRecyclerView.setAdapter(mCityMulitypeAdapter);

        mCityMulitypeAdapter.setItems(mCityItems);
        mCityMulitypeAdapter.notifyDataSetChanged();
    }

    private void initProvince() {
        mProvinceRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mPMulitypeAdapter = new MultiTypeAdapter();
        mPMulitypeAdapter.register(AreaCode.class, new AreaViewProvider(listener));
        mProvinceRecyclerView.setAdapter(mPMulitypeAdapter);

        mPMulitypeAdapter.setItems(mProvinceItems);
        mPMulitypeAdapter.notifyDataSetChanged();
    }

    private Observer<List<AreaCode>> mAreaListObserver = new Observer<List<AreaCode>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<AreaCode> value) {
            if (value != null && value.size() > 0) {
                if (value.get(0).isProvinceCode()) {
                    //省 列表
                    pageInde = 0;
                    mProvinceItems.clear();
                    mProvinceItems.addAll(value);
                    if (mPMulitypeAdapter != null) {
                        mPMulitypeAdapter.notifyDataSetChanged();
                    }
                } else {
                    //市 列表
                    mCityItems.clear();
                    mCityItems.addAll(value);
                    if (mCityMulitypeAdapter != null) {
                        mCityMulitypeAdapter.notifyDataSetChanged();
                    }
                    pageInde = 1;
                    mViewSwitcher.showNext();
                }
            }

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private Observer<List<CountyAreaCode>> mCountyAreaCodeObserver = new Observer<List<CountyAreaCode>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<CountyAreaCode> value) {
            if (value != null && value.size() > 0) {
                pageInde = 2;
                mSecondViewSwitcher.showNext();
                mCountyItems.clear();
                mCountyItems.addAll(value);
                if (mCountyMulitypeAdapter != null) {
                    mCountyMulitypeAdapter.notifyDataSetChanged();
                }
            }

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private Toast mToast;

    private void showToast(String msg) {
        if (getContext() == null) return;
        if (mToast == null) {
            mToast = Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }

    private OnItemClickListener listener = new OnItemClickListener() {
        @Override
        public void OnItemClick(View view, int position) {
            if (mItemClickListener != null) {
                mItemClickListener.OnItemClick(view, position);
            }
        }

        @Override
        public void OnItemClick(View view, Object object, int position) {

            if (object instanceof AreaCode) {
                AreaCode areaCode = (AreaCode) object;
                if (areaCode.isProvinceCode()) {
                    mProvinceAreaCode = areaCode;
                    getCitiesData(areaCode.getAreacode());
                } else {
                    mCityAreaCode = areaCode;
                    if (isNeedCountyCode) {
                        getCountysData(areaCode.getAreacode());
                    } else {
                        dismiss();
                    }
                }
            } else if (object instanceof CountyAreaCode) {
                mCountyAreaCode = (CountyAreaCode) object;
                dismiss();
            }
            if (mItemClickListener != null) {
                mItemClickListener.OnItemClick(view, object, position);
            }
        }
    };

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            if (pageInde > 1) {
                mSecondViewSwitcher.showPrevious();
                pageInde--;
                return true;
            } else if (pageInde > 0) {
                mViewSwitcher.showPrevious();
                pageInde--;
                return true;
            } else {
                dismiss();
            }
        }
        return false;
    }
}
